<template>
    <el-row :gutter="20" style="margin:10px -5px;min-height:500px" type="flex">
      <el-col style="width:280px" >
        <a-input-search style="margin-bottom: 8px" placeholder="请输入查询内容" @change="onChange" />
        <a-tree
          showLine
          @expand="onExpand"
          :expandedKeys="expandedKeys"
          :autoExpandParent="autoExpandParent"
          :treeData="gData"
          @select="this.onSelect"
        >
          <template slot="title" slot-scope="{title,key,parentId}">
            <span v-if="title.indexOf(searchValue) > -1">
              {{title.substr(0, title.indexOf(searchValue))}}
              <span style="color: #f50">{{searchValue}}</span>
              {{title.substr(title.indexOf(searchValue) + searchValue.length)}}
            </span>
            <span v-else>{{title}}</span>
            <a-dropdown :trigger="['click']">
                <a-icon type="bars" style="color:#409EFF"/>
                <a-menu slot="overlay">
                  <a-menu-item @click="handleAddOrgan">
                    <a-icon type="plus-circle" />添加子部门
                  </a-menu-item>
                  <a-menu-item @click="handleEditOrgan">
                    <a-icon type="edit" />修改名称
                  </a-menu-item>
                  <a-menu-divider v-if="parentId != '000000'"/>
                  <a-menu-item v-if="parentId != '000000'" @click="handleCanleOrgan(key)">
                    <a-icon type="delete" />删除部门
                  </a-menu-item>
                </a-menu>
              </a-dropdown>
          </template>
        </a-tree>
      </el-col>
      <el-col :span="18" style="border-left: #e9e9e9 solid 1px;min-height:500px">
        <el-row>
          <el-col :span="8">
            <p style="line-height:32px"><span>{{departmentName}}（{{parames.totalCount}}）人</span></p>
          </el-col>
          <el-col :span="8">
            <el-input size="small" clearable placeholder="请输入查询人员" v-model="parames.fuzzy" class="input-with-select">
              <el-button slot="append" icon="el-icon-search" @click="checkPage"></el-button>
            </el-input>
          </el-col>
          <el-col :span="8" style="text-align: right">
            <el-button size="small" @click="handleEditOrgan">修改部门名称</el-button>
            <el-button size="small" @click="handleAddOrgan">添加子部门</el-button>
          </el-col>
          <el-col :span="24" style="margin: 15px 0 8px 0;padding: 8px;background: rgba(240,240,240,0.65)">
            <el-button size="small" type="primary" @click="handleAddUser">添加成员</el-button>
            <el-button size="small" type="primary" @click="handleAddDepart">设置所在部门</el-button>
            <!-- <el-button size="small" type="primary" @click="handleOut">离职</el-button> -->
          </el-col>
          
          <el-col :span="24">
            <el-table
            :data="dataList"
            v-loading="loading"
            @selection-change="handleSelectionChange"
            border
            >
              <el-table-column
                type="selection"
                width="55">
              </el-table-column>
              <el-table-column
                prop="name"
                min-width="180"
                label="姓名">
              </el-table-column>
              <el-table-column
                prop="workNumber"
                min-width="180"
                label="工号">
              </el-table-column>
              <el-table-column
                prop="mobile"
                min-width="180"
                label="手机号">
              </el-table-column>
              <el-table-column
                prop="username"
                label="登录账号">
              </el-table-column>
              <el-table-column
                prop="departmentName"
                label="部门">
              </el-table-column>
              <el-table-column
                prop="email"
                label="邮箱">
              </el-table-column>
              <el-table-column
                width="120"
                label="操作"
                fixed="right"
                align="center">
                <template slot-scope="scope">
                    <el-button @click="handleEditUser(scope.row)" size="mini" type="text">查看</el-button>
                    <a-popconfirm
                      title="是否确认删除?"
                      @confirm="handleDelUser(scope.row)"
                      okText="是"
                      cancelText="否">
                        <el-button @click.stop="" size="mini" type="text">删除</el-button>
                    </a-popconfirm>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
          <pages :parames="parames" @render="checkPage"></pages>
        </el-row>
      </el-col>
      <organizationDialog :organizationData="organizationData" @checkRender="checkRender"></organizationDialog>
      <userDialog :userData="userData" @checkUser="checkUser"></userDialog>
      <departMentDialog :departData="departData" :treeData="gData" @checkUser="checkUser"></departMentDialog>
    </el-row>
</template>
<script>
  import organizationDialog from './editOrganization'
  import userDialog from './addUser'
  import departMentDialog from './setDepartMent'
  const gData = [];

  const getParentKey = (key, tree) => {
    let parentKey;
    for (let i = 0; i < tree.length; i++) {
      const node = tree[i];
      if (node.children) {
        if (node.children.some(item => item.key === key)) {
          parentKey = node.key;
        } else if (getParentKey(key, node.children)) {
          parentKey = getParentKey(key, node.children);
        }
      }
    }
    return parentKey;
  };
  export default {
    data() {
      return {
        loading: false,
        expandedKeys: [],
        searchValue: '',
        autoExpandParent: true,
        gData,
        dataList: [],
        parames: {
          companyId: '',
          departmentId: '',
          fuzzy: '',
          page: 1, //页码index
          limit: 10, //页码最大
          totalCount: 0,
        },
        treeList: [],
        multipleSelection: [],
        departmentName: '', //部门名称
        input3: '',
        userData: {
          show: false
        },
        departData: {
          departmentId: '',
          userIdList: [], //用户列表
          departmentName: '',
          type: '',
          show: false
        },
        organizationData: {
          type: '',
          parentId: '',
          title: '',
          companyId: '',
          show: false,
        }
      };
    },
    methods: {
      checkPage () { //页码改变
        if (this.organizationData.id) {
          this.getDepartmentUser()
        } else {
          this.getAllDepartmentUser()
        }
      },
      onExpand(expandedKeys) {
        this.expandedKeys = expandedKeys;
        this.autoExpandParent = false;
      },
      handleSelectionChange(val) { //选择用户成员
        this.multipleSelection = val;
      },
      handleAddDepart () { //设置所在部门
        if (this.multipleSelection.length == 0) {
          this.$alert('请选择用户','提示')
          return false
        }
        this.departData.userIdList = this.multipleSelection
        this.departData.show = true
      },
      handleCanleOrgan (key) { //删除部门
        if (this.dataList.length>0) {
          this.$alert('子部门人员删除才能进行删除操作!','提示')
          return false
        }
        this.$post(this.$api.postProviderOrganizationDel,{
          orgId: key
        }).then(response => {
          if (response.data.succeed) {
            this.getTree()
          }
        })
      },
      handleEditOrgan () { //修改部门
        if (this.organizationData.parentId == '') {
          this.$alert('请选择部门','提示')
          return false
        }
        this.organizationData.title = '修改部门名称'
        this.organizationData.type = 'editDepartment'
        this.organizationData.show = true
      },
      handleAddOrgan () { //新增子部门
        if (this.organizationData.parentId == '') {
          this.$alert('请选择父级部门','提示')
          return false
        }
        this.organizationData.type = 'newDepartment'
        this.organizationData.title = '添加子部门'
        this.organizationData.show = true
      },
      onSelect(selectedKeys, info) { //点击菜单树节点获取当前点击的部门
        if(selectedKeys.length != 0) {
          var node = info.selectedNodes[0].data.props.dataRef //菜单数据
          this.organizationData.id = node.id //部门id
          this.organizationData.parentId = node.parentId //父级id
          this.organizationData.companyId = node.companyId //服务商id
          this.organizationData.seqNum = node.seqNum //服务商id
          this.organizationData.label = node.label //部门名称
          this.departmentName = node.title //页面商部门名称
          this.userData.departmentId = node.id
          this.userData.departmentName = node.label
          this.parames.departmentId = node.id
          this.parames.companyId = node.companyId
          this.parames.page = 1
          this.getDepartmentUser()
        }
      },
      checkRender () {
        this.getTree()
      },
      checkUser () { //新增用户后刷新用户列表
      if (this.organizationData.id) {
          this.getDepartmentUser()
        } else {
          this.getAllDepartmentUser()
        }
        // this.getDepartmentUser()
      },
      onChange(e) { //查询组织架构
        const value = e.target.value;
        const expandedKeys = this.treeList.map(item => {
            if (item.title.indexOf(value) > -1) {
              return getParentKey(item.key, this.gData);
            }
            return null;
          })
          .filter((item, i, self) => item && self.indexOf(item) === i);
        Object.assign(this, {
          expandedKeys,
          searchValue: value,
          autoExpandParent: true,
        });
      },
      getAllDepartmentUser () { //获取服务商所有用户
        this.loading = true
        this.$post(this.$api.postProviderPersonelQueryList,{
          companyId: this.parames.companyId,
          departmentId: this.parames.departmentId,
          fuzzy: this.parames.fuzzy,
          start: this.parames.page, //页码index
          limit: this.parames.limit, //页码最大
        }).then(response => {
          if (response.data.succeed) {
            this.dataList = response.data.data
            this.parames.totalCount = response.data.totalCount
            setTimeout(() => {
              this.loading = false
            }, 200);
          }
        })
      },
      getDepartmentUser () { //获取部门下的用户
        this.loading = true
        this.$post(this.$api.postProviderPersonelQueryDepartmentList,{
          departmentId: this.parames.departmentId,
          fuzzy: this.parames.fuzzy,
          start: this.parames.page, //页码index
          limit: this.parames.limit, //页码最大
        }).then(response => {
          if (response.data.succeed) {
            this.dataList = response.data.data
            this.parames.totalCount = response.data.totalCount
            setTimeout(() => {
              this.loading = false
            }, 200);
          }
        })
      },
      generateList (data) { //树的搜索
        for (let i = 0; i < data.length; i++) {
          const node = data[i];
          const key = node.key;
          this.treeList.push({ key, title: node.title});
          if (node.children) {
            this.generateList(node.children, node.key);
          }
        }
      },
      handleAddUser () { //在部门上添加成员
        if (this.organizationData.parentId == '') {
          this.$alert('请选择部门','提示')
          return false
        }
        this.userData.type = "new"
        this.userData.title = "添加成员"
        this.userData.show = true
      },
      handleEditUser (row) { //修改部门上的成员
        this.userData.type = "edit"
        this.userData.title = "编辑成员"
        this.userData.id = row.id
        this.userData.show = true
      },
      handleDelUser (row) { //删除用户
        this.$post(this.$api.postProviderPersonelDel,{
          empId: row.id
        }).then(response => {
          if (response.data.succeed) {
            if (this.organizationData.id) {
              this.getDepartmentUser()
            } else {
              this.getAllDepartmentUser()
            }
          }
        })
      },
      handleOut () { //离职
        this.$message({message:'请选择用户',type:'warning'})
      },
      getTree() { //获取组织架构树
        this.$post(this.$api.postProviderOrganizationQueryList).then(response => {
          if (response.data.succeed) {
            this.gData = []
            if (!this.organizationData.id) {
              this.departmentName = '全部'
              this.organizationData.companyId = response.data.data[0].companyId
              this.parames.companyId = response.data.data[0].companyId
              this.parames.page = 1
              this.getAllDepartmentUser() //获取所有人员的数据
            }
            
            if (response.data.data.length > 0) {
              response.data.data.forEach(el=>{
                this.getData(el)
                if (el.title) {
                  this.gData.push(el)
                }
              })
              this.generateList(this.gData)
            }
            
          }
        })
      },
      getData(data) { //处理树数据
        data.title = data.label
        data.key = data.id //
        data.scopedSlots = { title: 'title', key: 'key', parentId: 'parentId' }
        if (data.children && data.children.length > 0) {
          for(var i = 0; i < data.children.length; i++) {
            this.getData(data.children[i])
          }
        }
      }
    },
    mounted() {
      this.getTree()
    },
    components: {
      organizationDialog,
      userDialog,
      departMentDialog
    }
  };
</script>
